#include <Arduino.h>
#include <SPI.h>

#define  CSPIN 10
uint8_t RGB[4];
uint8_t flag;

void Init3265B(void);
void SPI_WriteByte(uint8_t Reg_Add,uint8_t Reg_Dat);

void setup() {
  //pinMode(13, OUTPUT);
    pinMode (CSPIN, OUTPUT);
  digitalWrite(CSPIN,HIGH);
  Serial.begin(9600);
  //digitalWrite(13, LOW);
  SPI.begin();
  //SPI.beginTransaction(SPISettings(20000000, MSBFIRST, SPI_MODE0));
  //SPI.setClockDivider(SPI_CLOCK_DIV4);
  SPI.setDataMode(3);
  Init3265B();
  delay(1000);

}

void loop() {
  static uint8_t temp;
  if(flag == 5)
  {
    if(RGB[3] == 0x01)
    {
      SPI_WriteByte(0x20,RGB[0]);
      SPI_WriteByte(0x1F,RGB[1]);
      SPI_WriteByte(0x21,RGB[2]);
      SPI_WriteByte(0x2F,RGB[0]);
      SPI_WriteByte(0x2E,RGB[1]);
      SPI_WriteByte(0x30,RGB[2]);
      SPI_WriteByte(0x37,0x00);
    }else if(RGB[3] == 0x02)
    {
      SPI_WriteByte(0x23,RGB[0]);
      SPI_WriteByte(0x22,RGB[1]);
      SPI_WriteByte(0x24,RGB[2]);
      SPI_WriteByte(0x2C,RGB[0]);
      SPI_WriteByte(0x2B,RGB[1]);
      SPI_WriteByte(0x2D,RGB[2]);
      SPI_WriteByte(0x37,0x00);     
    }else if(RGB[3] == 0x03)
    {
      SPI_WriteByte(0x26,RGB[0]);
      SPI_WriteByte(0x25,RGB[1]);
      SPI_WriteByte(0x27,RGB[2]);
      SPI_WriteByte(0x29,RGB[0]);
      SPI_WriteByte(0x28,RGB[1]);
      SPI_WriteByte(0x2A,RGB[2]);
      SPI_WriteByte(0x37,0x00);
    }
  }
  if (Serial.available() > 0) {
    temp = Serial.read();
    if(temp == 0x55)//start
    {
      if(flag == 0)
        flag = 1;
    }else if(flag > 0 && flag < 5)
    {
      RGB[flag-1] = temp;
      flag++;
    }else if(flag > 4)
    {
      if(temp == 0x0a)
        flag = 0;
    }
  }
}

void SPI_WriteByte(uint8_t Reg_Add,uint8_t Reg_Dat) //write register
{
  digitalWrite(CSPIN, LOW); // take the SS pin low to select the chip:
  SPI.transfer(Reg_Add);
  SPI.transfer(Reg_Dat);
  digitalWrite(CSPIN, HIGH); // take the SS pin high to de-select the chip:
}

uint8_t SPI_ReadByte(uint8_t address)
{
  digitalWrite(CSPIN,LOW);
  //SPI.transfer(0x05);
  SPI.transfer(address);
  uint8_t result = SPI.transfer(0xFF);
  digitalWrite(CSPIN, HIGH);
  return result;
}

void Init3265B(void)
{
  int i,j;
  SPI_WriteByte(0x00,0x01);//normal mode
  for(i=0x02;i<0x14;i++)
  {
    SPI_WriteByte(i,0xff);//scaling
  }
  for(i=0x1F;i<0x31;i++)
  {
    SPI_WriteByte(i,0x03);//pwm
  }
  SPI_WriteByte(0x36,0x00);//scaling update
  SPI_WriteByte(0x37,0x00);//pwm update
  SPI_WriteByte(0x01,0x20);//gcc
}